package com.ruoyi.training.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.training.domain.*;
import com.ruoyi.training.dto.certificate.CertificateIssueDto;
import com.ruoyi.training.dto.certificate.CertificateTemplateDto;
import com.ruoyi.training.dto.certificate.GenerateElectronicSelectDto;
import com.ruoyi.training.dto.certificate.ViewElectronicDto;
import com.ruoyi.training.dto.registration.RegistrationDto;
import com.ruoyi.training.mapper.*;
import com.ruoyi.training.service.ICertificateIssueService;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.certificate.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 证书发放管理Service业务层处理
 * 
 * @author hcc
 * @date 2025-11-06
 */
@Service
public class CertificateIssueServiceImpl implements ICertificateIssueService
{
    @Autowired
    private CertificateIssueMapper certificateIssueMapper;

    @Autowired
    private ProjectsMapper projectsMapper;

    @Autowired
    private TrainingClassMapper trainingClassMapper;

    @Autowired
    private CertificateTemplateMapper certificateTemplateMapper;

    @Autowired
    private CertificateFieldMapper certificateFieldMapper;

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private PaymentRecordMapper paymentRecordMapper;

    @Autowired
    private InvoiceMapper invoiceMapper;
    /**
     * 查询证书发放管理
     * 
     * @param certificateIssueId 证书发放管理主键
     * @return 证书发放管理
     */
    @Override
    public CertificateIssue selectCertificateIssueByCertificateIssueId(String certificateIssueId)
    {
        return certificateIssueMapper.selectCertificateIssueByCertificateIssueId(certificateIssueId);
    }

    /**
     * 查询证书发放管理列表
     * 
     * @param certificateIssue 证书发放管理
     * @return 证书发放管理
     */
    @Override
    public List<CertificateIssue> selectCertificateIssueList(CertificateIssue certificateIssue)
    {
        return certificateIssueMapper.selectCertificateIssueList(certificateIssue);
    }

    /**
     * 新增证书发放管理
     * 
     * @param certificateIssue 证书发放管理
     * @return 结果
     */
    @Override
    public int insertCertificateIssue(CertificateIssue certificateIssue)
    {
        certificateIssue.setCertificateIssueId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
        return certificateIssueMapper.insertCertificateIssue(certificateIssue);
    }

    /**
     * 修改证书发放管理
     * 
     * @param certificateIssue 证书发放管理
     * @return 结果
     */
    @Override
    public int updateCertificateIssue(CertificateIssue certificateIssue)
    {
        return certificateIssueMapper.updateCertificateIssue(certificateIssue);
    }

    /**
     * 批量删除证书发放管理
     * 
     * @param certificateIssueIds 需要删除的证书发放管理主键
     * @return 结果
     */
    @Override
    public int deleteCertificateIssueByCertificateIssueIds(String[] certificateIssueIds)
    {
        return certificateIssueMapper.deleteCertificateIssueByCertificateIssueIds(certificateIssueIds);
    }

    /**
     * 删除证书发放管理信息
     * 
     * @param certificateIssueId 证书发放管理主键
     * @return 结果
     */
    @Override
    public int deleteCertificateIssueByCertificateIssueId(String certificateIssueId)
    {
        return certificateIssueMapper.deleteCertificateIssueByCertificateIssueId(certificateIssueId);
    }

    /**
     * 查询证书发放管理列表
     *
     * @param certificateIssueVo 证书发放管理
     * @return 列表
     */
    @Override
    public List<CertificateIssueDto> getCertificateIssueList(CertificateIssueVo certificateIssueVo) {
        List<CertificateIssueDto> certificateIssueDtoList = certificateIssueMapper.getCertificateIssueList(certificateIssueVo);
        List<CertificateIssueDto> collect = certificateIssueDtoList.stream().map(certificateIssueDto -> {
            Projects projects = projectsMapper.selectProjectsByProjectId(certificateIssueDto.getProjectId());
            if (projects != null) {
                certificateIssueDto.setProjectName(projects.getProjectName());
            }
            if (StringUtils.isNotEmpty(certificateIssueDto.getRegistrationId())){
                RegistrationDto registrationDto = registrationMapper.selectRegistrationByRegistrationId(certificateIssueDto.getRegistrationId());
                if (registrationDto != null) {
                    certificateIssueDto.setRegistrationMethod(registrationDto.getRegistrationMethod());
                    certificateIssueDto.setRecordStatus(registrationDto.getRecordStatus());
                    certificateIssueDto.setRecordMissing(registrationDto.getRecordMissing());
                    certificateIssueDto.setRegistrationTime(registrationDto.getCreateTime());
                }
            }
            if (StringUtils.isNotEmpty(certificateIssueDto.getInvoiceId())){
                Invoice invoice = invoiceMapper.selectInvoiceByInvoiceId(certificateIssueDto.getInvoiceId());
                if (invoice != null) {
                    certificateIssueDto.setInvoiceStatus(invoice.getInvoiceStatus());
                }
            }
            if (StringUtils.isNotEmpty(certificateIssueDto.getPaymentId())){
                PaymentRecord paymentRecord = paymentRecordMapper.selectPaymentRecordByPaymentRecordId(certificateIssueDto.getPaymentId());
                if (paymentRecord != null) {
                    certificateIssueDto.setPaymentState(paymentRecord.getPaymentState());
                    certificateIssueDto.setCertificateReissueFee(paymentRecord.getPaymentAmount());
                }
            }
            return certificateIssueDto;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 添加证书发放管理
     *
     * @param certificateIssue 添加证书发放管理
     * @return 添加结果
     */
    @Override
    public int addCertificateIssue(CertificateIssue certificateIssue) {
        certificateIssue.setCertificateIssueId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
        certificateIssue.setCertificateType("1");
        certificateIssue.setDigitalStatus("3");
        certificateIssue.setPaperStatus("1");
        certificateIssue.setImmediatePublish("1");
        return 0;
    }

    /**
     * 生成电子证书数据查询
     *
     * @param generateElectronicSelectVo 生成电子证书数据查询
     * @return 列表
     */
    @Override
    public GenerateElectronicSelectDto getGenerateElectronicSelect(GenerateElectronicSelectVo generateElectronicSelectVo) {
        List<CertificateTemplate> certificateTemplates = new ArrayList<>();
        if (StringUtils.isNotEmpty(generateElectronicSelectVo.getTrainingClassId())){
            TrainingClass trainingClass = trainingClassMapper.selectTrainingClassByTrainingClassId(generateElectronicSelectVo.getTrainingClassId());
            if (StringUtils.isNotNull(trainingClass)){
                String[] split = trainingClass.getCertificateId().split(",");
                for (String s : split) {
                    CertificateTemplate certificateTemplate = certificateTemplateMapper.selectCertificateTemplateByCertificateTemplateId(s);
                    certificateTemplates.add(certificateTemplate);
                    List<CertificateField> certificateFields = certificateFieldMapper.selectCertificateFieldByCertificateTemplateId(certificateTemplate.getCertificateTemplateId());
                    certificateTemplate.setCertificateFieldList(certificateFields);
                }
            }
        }else {
            certificateTemplates = certificateTemplateMapper.selectCertificateTemplateList(null);
            for (CertificateTemplate certificateTemplate : certificateTemplates) {
                List<CertificateField> certificateFields = certificateFieldMapper.selectCertificateFieldByCertificateTemplateId(certificateTemplate.getCertificateTemplateId());
                certificateTemplate.setCertificateFieldList(certificateFields);
            }
        }
        List<CertificateIssueDto> certificateIssueDtoList = certificateIssueMapper.selectCertificateIssueByCertificateIssueIds(generateElectronicSelectVo.getCertificateIssueIds());
        GenerateElectronicSelectDto generateElectronicSelectDto = new GenerateElectronicSelectDto();
        generateElectronicSelectDto.setCertificateIssueDtoList(certificateIssueDtoList);
        generateElectronicSelectDto.setCertificateTemplateList(certificateTemplates);
        return generateElectronicSelectDto;
    }

    /**
     * 生成电子证书
     *
     * @param generateElectronicVo 生成电子证书
     * @return 生成结果
     */
    @Override
    public int generateElectronic(GenerateElectronicVo generateElectronicVo) {
        List<CertificateIssue> certificateIssueList = generateElectronicVo.getCertificateIssueList();
        int i = 0;
        if (StringUtils.isEmpty(certificateIssueList)){
            return 0;
        }
        for (CertificateIssue certificateIssue : certificateIssueList) {
            if ("1".equals(generateElectronicVo.getImmediatePublish())){
                certificateIssue.setDigitalStatus("1");
            }
            certificateIssue.setImmediatePublish(generateElectronicVo.getImmediatePublish());
            certificateIssue.setDigitalIssueTime(generateElectronicVo.getDigitalIssueTime());
            certificateIssue.setUpdatedBy(SecurityUtils.getUsername());
            certificateIssue.setUpdatedTime(DateUtils.getNowDate());
            i = certificateIssueMapper.updateCertificateIssue(certificateIssue);
        }
        return i;
    }

    /**
     * 取消电子证书
     *
     * @param cancelElectronicVo 取消电子证书
     * @return 删除结果
     */
    @Override
    public int cancelElectronic(CancelElectronicVo cancelElectronicVo) {
        List<CertificateIssue> certificateIssueList = cancelElectronicVo.getCertificateIssueList();
        int i = 0;
        if (StringUtils.isEmpty(certificateIssueList)){
            return 0;
        }
        for (CertificateIssue certificateIssue : certificateIssueList) {
            certificateIssue.setDigitalStatus("2");
            certificateIssue.setTemplateId("");
            certificateIssue.setRevokeReason(cancelElectronicVo.getRevokeReason());
            certificateIssue.setUpdatedBy(SecurityUtils.getUsername());
            certificateIssue.setUpdatedTime(DateUtils.getNowDate());
            i = certificateIssueMapper.updateCertificateIssue(certificateIssue);
        }
        return i;
    }

    /**
     * 查看电子证书信息
     *
     * @param certificateIssueIds 查看电子证书信息
     * @return 列表
     */
    @Override
    public List<ViewElectronicDto> getElectronicInfo(String[] certificateIssueIds) {
        List<ViewElectronicDto> viewElectronicDtoList = new ArrayList<>();
        for (String certificateIssueId : certificateIssueIds) {
            CertificateIssue certificateIssue = certificateIssueMapper.selectCertificateIssueByCertificateIssueId(certificateIssueId);
            ViewElectronicDto viewElectronicDto = new ViewElectronicDto();
            Students students = studentsMapper.selectStudentsByStudentId(certificateIssue.getStudentId());
            if (StringUtils.isNotNull(students)){
                viewElectronicDto.setStudentName(students.getStudentName());
                viewElectronicDto.setIdNumber(students.getIdNumber());
            }
            Projects projects = projectsMapper.selectProjectsByProjectId(certificateIssue.getProjectId());
            if (StringUtils.isNotNull(projects)){
                viewElectronicDto.setProjectName(projects.getProjectName());
            }
            if (StringUtils.isNotNull(certificateIssue)){
                BeanUtils.copyProperties(certificateIssue,viewElectronicDto);
                if(StringUtils.isNotEmpty(certificateIssue.getTemplateId())){
                    // 获取证书模板信息
                    CertificateTemplate certificateTemplate = certificateTemplateMapper.selectCertificateTemplateByCertificateTemplateId(certificateIssue.getTemplateId());
                    // 获取证书字段信息
                    List<CertificateField> certificateFields = certificateFieldMapper.selectCertificateFieldByCertificateTemplateId(certificateIssue.getTemplateId());
                    List<CertificateField> collect = certificateFields.stream().map(certificateField -> {
                        if ("name".equals(certificateField.getFieldKey())) {
                            certificateField.setExampleOne(viewElectronicDto.getStudentName());
                        } else if ("idNumber".equals(certificateField.getFieldKey())) {
                            certificateField.setExampleOne(viewElectronicDto.getIdNumber());
                        } else if ("trainingProject".equals(certificateField.getFieldKey())) {
                            certificateField.setExampleOne(viewElectronicDto.getProjectName());
                        } else if ("validYears".equals(certificateField.getFieldKey()) && certificateIssue.getDigitalIssueTime() != null) {
                            certificateField.setExampleOne(DateUtils.parseDateToStr("yyyy-MM-dd", certificateIssue.getDigitalIssueTime()));
                        } else if ("issueDate".equals(certificateField.getFieldKey()) && certificateIssue.getDigitalIssueTime() != null) {
                            certificateField.setExampleOne(DateUtils.parseDateToStr("yyyy-MM-dd", certificateIssue.getDigitalIssueTime()));
                        } else if ("startDate".equals(certificateField.getFieldKey()) && certificateIssue.getValidityStart() != null) {
                            certificateField.setExampleOne(DateUtils.parseDateToStr("yyyy-MM-dd", certificateIssue.getValidityStart()));
                        } else if ("endDate".equals(certificateField.getFieldKey()) && certificateIssue.getValidityEnd() != null) {
                            certificateField.setExampleOne(DateUtils.parseDateToStr("yyyy-MM-dd", certificateIssue.getValidityEnd()));
                        }else {
                            certificateField.setExampleOne(certificateField.getFieldLabel());
                        }
                        return certificateField;
                    }).collect(Collectors.toList());
                    CertificateTemplateDto certificateTemplateDto = new CertificateTemplateDto();
                    BeanUtils.copyProperties(certificateTemplate, certificateTemplateDto);
                    certificateTemplateDto.setCertificateFieldList(collect);
                    viewElectronicDto.setCertificateTemplateDto(certificateTemplateDto);
                    viewElectronicDtoList.add(viewElectronicDto);
                }

            }
        }
        return viewElectronicDtoList;
    }

    /**
     * 快递电子证书
     *
     * @param expressElectronicVo 快递电子证书
     * @return 快递结果
     */
    @Override
    public int expressPaperCertificate(ExpressElectronicVo expressElectronicVo) {
        List<CertificateIssue> certificateIssueList = expressElectronicVo.getCertificateIssueList();
        int i = 0;
        if (StringUtils.isEmpty(certificateIssueList)){
            return 0;
        }
        for (CertificateIssue certificateIssue : certificateIssueList) {
            certificateIssue.setPaperStatus("1"); // 纸质已发放
            certificateIssue.setPaperIssueTime(DateUtils.getNowDate());
            certificateIssue.setReceiveMethod("2"); // 快递
            certificateIssue.setUpdatedTime(DateUtils.getNowDate());
            certificateIssue.setUpdatedBy(SecurityUtils.getUsername());
            i = certificateIssueMapper.updateCertificateIssue(certificateIssue);
        }
        return i;
    }

    /**
     * 现场领取证书
     *
     * @param certificateIssueIds 场景纸质证书
     * @return 添加结果
     */
    @Override
    public int scenePaperCertificate(String[] certificateIssueIds) {
        return certificateIssueMapper.updateByCertificateIssueIds(certificateIssueIds);
    }
}
